package com.imooc.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Wang Renlei
 * @Date 2021/10/10 0015
 */
@Slf4j
public class JsonUtils2 {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    //注意：jackson格式不一样，下面设置的方式也不一样
    static {
        //序列化所有字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //忽略null的属性
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //date默认会转换为timestamps形式。这里设置取消转换
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //忽略空bean转json的错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //统一时间转字符串格式，即：yyyy-MM-dd HH:mm:ss
//        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.yyyyMMddHHmmss));

        //反序列化
        //忽略 在json字符串中存在，但在java对象中不存在对应属性的情况，防止错误
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    //对象转字符串
    public static <T> String objToString(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            //传的是字符串就之间返回
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse Object to String error", e);
            return null;
        }
    }

    //返回格式化好的json 字符串
    public static <T> String objToStringPretty(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            //传的是字符串就之间返回
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse Object to String error", e);
            return null;
        }
    }

    //字符串转对象
    public static <T> T stringToObj(String str, Class<T> clazz) {
        if (StringUtils.isEmpty(str) || clazz == null) {
            return null;
        }
        try {
            return clazz.equals(String.class) ? (T) clazz : objectMapper.readValue(str, clazz);
        } catch (Exception e) {
            log.warn("Parse String to Object error", e);
            return null;
        }
    }

    //字符串转对象。集合泛型
    public static <T> T stringToObj(String str, TypeReference<T> reference) {
        if (StringUtils.isEmpty(str) || reference == null) {
            return null;
        }
        try {
            return (T) (reference.getType().equals(String.class) ? str : objectMapper.readValue(str, reference));
        } catch (Exception e) {
            log.warn("Parse String to Object error", e);
            return null;
        }
    }


    //字符串转对象。集合、集合中的元素（可以是多个不同类型元素）
    //参数使用?而不使用T，表示可以传入多种Class类型
    public static <T> T stringToObj(String str, Class<?> collectionClass, Class<?>... elementClasses) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        try {
            return objectMapper.readValue(str, javaType);
        } catch (Exception e) {
            log.warn("Parse String to Object error", e);
            return null;
        }
    }
}
